package com.knowledgegraph.repository;

import com.knowledgegraph.entity.Node;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface NodeRepository extends JpaRepository<Node, Long> {
    
    Optional<Node> findByName(String name);
    
    List<Node> findByNodeType(String nodeType);
    
    List<Node> findByNameContainingIgnoreCase(String name);
    
    @Query("SELECT n FROM Node n WHERE n.nodeType = :nodeType AND n.name LIKE %:name%")
    List<Node> findByNodeTypeAndNameContaining(@Param("nodeType") String nodeType, @Param("name") String name);
    
    @Query("SELECT DISTINCT n.nodeType FROM Node n")
    List<String> findAllNodeTypes();
    
    @Query("SELECT COUNT(n) FROM Node n WHERE n.nodeType = :nodeType")
    Long countByNodeType(@Param("nodeType") String nodeType);
    
    @Query("SELECT n FROM Node n WHERE n.id IN " +
           "(SELECT DISTINCT nr.sourceNode.id FROM NodeRelation nr WHERE nr.targetNode.id = :nodeId) " +
           "OR n.id IN " +
           "(SELECT DISTINCT nr.targetNode.id FROM NodeRelation nr WHERE nr.sourceNode.id = :nodeId)")
    List<Node> findConnectedNodes(@Param("nodeId") Long nodeId);
    
    @Query("SELECT n FROM Node n WHERE n.id IN " +
           "(SELECT DISTINCT nnr.node.id FROM NodeResource nnr WHERE nnr.resource.id = :resourceId)")
    List<Node> findNodesByResourceId(@Param("resourceId") Long resourceId);
}